/**
 * problem_022.c
 * Copyright (C) 2011-03-20 - xrose
 */

#include <stdio.h>
#include <string.h>
#include "e_sort.h"

int main (int argc, char *argv[])
{
    char fs_name[] = "names.txt";
    char fd_name[] = "stdzise.txt";

    int i, j, k;

    stdzise(fs_name, fd_name);

    char l_word[w_lst_max][w_sz_max+1];
    char tmp[w_sz_max + 1];
    char str[mx_sz_buff];
    FILE *p_fd;
    p_fd = fopen(fd_name, "r");
    if (p_fd==NULL) printf("Error opening %s file", fd_name);
    fgets (str , mx_sz_buff , p_fd);
    fclose(p_fd);
    i = 0;
    k =0;
    while((str[i] != '\0')&&(str[i]!=10))
    {
        j = 0;
        for(j=0; j<=w_sz_max; j++)
        {
            if(str[i+j] != ',')
            {
                tmp[j] = str[i+j];
            } else
            {
                tmp[j]='\0';
            }
        }
        strcpy(l_word[k], tmp);
        i+=(w_sz_max+1);
        k++;
    }

    l_word[k][0] = NULL;
    printf("l_word[0] = %s\n", l_word[0]);
    printf("compute_word(l_word[0]) = %d\n", compute_word(l_word[0]));
    wb_sort(l_word);

    //Write to file:
    p_fd = fopen(fd_name, "w");
    if (p_fd==NULL) printf("Error opening %s file", fd_name);
    i=0;
    while(l_word[i][0]!=NULL)
    {
        fprintf (p_fd, "%s\n",l_word[i]);
        i++;
    }
    fclose(p_fd);
    printf("compute(l_word) = %d", compute(l_word));
    return 0;
}
int compute(char lst_word[][w_sz_max+1])
{
    int _sum = 0, i=0;
    while(lst_word[i][0] != NULL)
     {
        _sum +=(compute_word(lst_word[i])*(i+1));
        i++;
     }
     return _sum;
}
int compute_word(char _word[w_sz_max+1])
{
    int i = 0;
    int _sum = 0;
    s_toupper(_word);
    for(i =0; i<=w_sz_max; i++)
    {
        if((_word[i] != '0')&&(_word[i]!='\0'))
        {
            printf("compute_word() c[%d] = %c; sum = %d; A = %d\n", i, _word[i], _sum, 'A');
            _sum += (int)_word[i] - 'A' + 1;
        }
    }
    return _sum;
}
